const { checkIsExistByName } = require('../models/user')
const { createFail } = require('../utils/')

function checkUserRegister(req, res, next) {
  const {
    body: { username, password }
  } = req

  if (!username || !password) {
    return res.json(createFail('用户名或密码不能为空'))
  } else {
    checkIsExistByName(username)
      .then(result => {
        if (result.length > 0) {
          res.json(createFail('用户名已存在'))
        } else {
          next()
        }
      })
      .catch(err => {
        console.log(err)
        res.json(createFail('数据库异常'))
      })
  }
}

module.exports = checkUserRegister
